import time
from typing import Any, Optional
import queue
from core.thread.protocol import Readable, Writable


# ---------- 本地 Queue 适配 ----------
class LocalQueueAdapter(Readable, Writable):
    """将标准库 queue.Queue 适配为 read()/write() 接口"""

    def __init__(self, q: queue.Queue):
        self.q = q

    def read(self, batch_size: int = 1, timeout: Optional[float] = None):
        items: list[Any] = []
        if batch_size <= 1:
            try:
                return self.q.get(timeout=timeout) if timeout else self.q.get()
            except queue.Empty:
                return None
        # 批量尽力取
        deadline = (time.time() + timeout) if timeout else None
        while len(items) < batch_size:
            remaining = max(0.0, deadline - time.time()) if deadline else None
            try:
                i = (
                    self.q.get(timeout=remaining)
                    if remaining is not None
                    else self.q.get_nowait()
                )
                items.append(i)
            except queue.Empty:
                break
        return items

    def write(self, item: Any) -> None:
        self.q.put(item)
